<?php

class Core_Model_DbTable_Pages extends YouNet_Db_Table
{
	const TABLE_NAME = 'pages';
	protected $_name = self::TABLE_NAME;
	protected $_rowClass = 'Core_Model_Page';
	protected $_primary = array('id_page', 'id_store');
	protected $_referenceMap = array(
		'Store' => array(
			'columns' => array('id_store'),
			'refTableClass' => 'Core_Model_DbTable_Stores',
			'refColumns' => array('id')
		)
	);
	
	static private $_instance;
	
	/**
	 *
	 * @return Core_Model_DbTable_Pages
	 */
	public static function getInstance()
	{
		if (!(self::$_instance instanceof Core_Model_DbTable_Pages))
		{
			self::$_instance = new Core_Model_DbTable_Pages();
		}
		return self::$_instance;
	}
	
	public function updateFanpage(array $arrPageList, array $arrFanpageIds, $id_store = null)
	{
		$arrPages = $arrPageList;
		foreach ($arrPages as $id_page => $name_page)
		{
			$pageRow = $this->findOne($id_page, $id_store);
			if (in_array($id_page, $arrFanpageIds))
			{
				if (empty($pageRow))
				{
					$pageRow = $this->createRow();
				}
				$pageRow->id_page = $id_page;
				//fix bug explode by comma in list
				$pageRow->name = str_replace(',', '&#44;', $name_page);
				$pageRow->id_store = $id_store;
				$pageRow->save();
			}
			else
			{
				if (!empty($pageRow))
				{
					$pageRow->delete();
				}
			}
		}
	}
	
	/**
	 * @param string $id_page
	 */
	public function hasShowStore($id_page)
	{
		$select  = $this->select()->setIntegrityCheck(false)
					->from(array('p'=>self::TABLE_NAME),array('count(*) AS has_store'))
					->joinLeft(array('s'=>Core_Model_DbTable_Stores::TABLE_NAME), 's.id = p.id_store',array())
					->where('p.id_page = ?', $id_page)
					->where('s.status = ?', Core_Model_DbTable_Stores::STATUS_SHOWN)
					->limit(1);
		return $this->fetchAll($select)->current();
	}
	
	public function getPublishedStores($arrIdPages)
	{
		$select  = $this->select()->setIntegrityCheck(false)
					->from(array('p'=>self::TABLE_NAME),array('GROUP_CONCAT(p.id_page) as id_pages'))
					->joinLeft(array('s'=>Core_Model_DbTable_Stores::TABLE_NAME), 's.id = p.id_store',array())
					->where('p.id_page IN(?)', $arrIdPages)
					->where('s.status = ?', Core_Model_DbTable_Stores::STATUS_SHOWN);
		return $this->fetchAll($select)->current();
	}
}